width = 250
height = 250
deep = 100

import os

def manfunc(x,y):
    z = 0+0j 
    c = complex(x,y)
    i = 0
    while abs(z) < 2:
        z = z*z+c
        i += 1
        if i >= deep: break
    return i - 1

from random import randint

def get_palette(size):
    for x in range(size):
        yield (
            randint(0, 255),
            randint(0, 255),
            randint(0, 255)
        )

palette = [(89, 225, 20), (117, 157, 123), (145, 221, 143), (163, 241, 177), (163, 123, 223), (114, 177, 191), (138, 47, 50), (20, 69, 81), (136, 26, 90), (156, 87, 128), (61, 227, 128), (134, 101, 39), (143, 128, 244), (37, 172, 244), (246, 126, 73), (232, 174, 104), (200, 129, 12), (95, 64, 102), (177, 201, 200), (133, 148, 204), (4, 130, 234), (167, 99, 58), (93, 133, 146), (235, 90, 144), (238, 237, 152), (15, 89, 141), (86, 22, 52), (244, 30, 73), (80, 1, 99), (156, 161, 48), (190, 69, 23), (89, 68, 137), (72, 36, 28), (41, 28, 142), (70, 133, 213), (197, 57, 41), (25, 153, 241), (149, 26, 30), (51, 62, 196), (214, 54, 192), (162, 0, 27), (67, 158, 62), (9, 65, 45), (196, 15, 1), (226, 150, 105), (140, 7, 162), (8, 30, 85), (8, 214, 219), (237, 61, 162), (190, 59, 140), (98, 238, 5), (155, 71, 25), (224, 197, 40), (24, 194, 73), (235, 220, 212), (102, 183, 135), (93, 53, 159), (135, 162, 45), (204, 65, 220), (141, 31, 83), (74, 95, 88), (128, 8, 241), (54, 138, 152), (237, 112, 97), (39, 58, 231), (206, 33, 101), (99, 230, 21), (196, 77, 125), (102, 94, 176), (86, 99, 22), (43, 250, 49), (61, 195, 0), (14, 108, 26), (190, 102, 101), (68, 1, 11), (173, 224, 85), (63, 74, 54), (239, 33, 39), (9, 93, 234), (246, 205, 45), (139, 114, 54), (138, 154, 233), (246, 44, 252), (228, 227, 140), (33, 56, 185), (58, 5, 177), (160, 160, 156), (83, 135, 249), (14, 24, 14), (116, 146, 201), (218, 70, 15), (171, 122, 148), (224, 152, 46), (246, 250, 181), (53, 33, 220), (94, 96, 136), (44, 43, 27), (113, 211, 167), (11, 47, 65), (214, 28, 202)]

def yield_mandelbrot(width, height, x1, y1, x2, y2):
    w = (x2 - x1) / width
    h = (y2 - y1) / height
    for y in range(height):
        for x in range(width):
            val = manfunc(x1 + x * w, y1 + y * h)
            yield palette[val][0]
            yield palette[val][1]
            yield palette[val][2]

from pyglet import image

def get_tile(x, y, d, path):
    filename = path + '{}_{}_{}.png'.format(x, y, d)
    print(filename)
    if os.path.exists(filename):
        return filename
    print('generating')
    d = d / 2
    x1, y1, x2, y2 = x - d, y - d, x + d, y + d
    img = image.create(width, height)
    img.set_data('RGB', width * 3, bytes(
        yield_mandelbrot(width, height, x1, y1, x2, y2)
    ))
    img.format = 'RGB'
    img.save(filename)
    return filename
